#include "RunLengthEncoder.h"
#include <stdio.h>

RunLengthEncoder::RunLengthEncoder()
{
}

RunLengthEncoder::~RunLengthEncoder()
{
}

void RunLengthEncoder::Write(const void *data, unsigned int size)
{
	unsigned char* byteData = (unsigned char*) data;
	unsigned int index = 0, count = 0;

	while(index < size)
	{
		count = 0;
		while(index < size && byteData[index] == 0)
		{
			index++;
			count++;
		}

		if (index >= size)
			break;

		while(count > 254)
		{
			unsigned char FF = 255;

			count = count - 255;
			BufferedByteStream::Write(&FF, 1);
		}

		BufferedByteStream::Write(&count, 1);
		BufferedByteStream::Write(&byteData[index], 1);
		
		index++;
		count = 0;
	}

	if (count)
	{
		count--;
		BufferedByteStream::Write(&count, 1);
		count = 0;
		BufferedByteStream::Write(&count, 1);
	}
}
